# encoding=utf-8
import json
import os
import tempfile
from flask import Response, send_file, make_response
from seg_common.Paser import ParserTools
from openpyxl import Workbook


class DownloadExcelService:
    def make_excel(self, seg_saver, vascular_saver, img_list: list, all_img: bool, lang_dict: dict):
        if all_img:
            img_list = self.get_all_img(seg_saver.NORMAL_0)
        else:
            img_list = self.chang_suffix(img_list)

        d = self.make_result_dict(seg_saver, vascular_saver, img_list)
        excel_file = self.generate_excel(d, lang_dict)
        return self.send_excel_file(excel_file)

    def send_excel_file(self, file_name):
        response = make_response(send_file(file_name, os.path.basename(file_name), as_attachment=True))
        response.headers["Access-Control-Expose-Headers"] = "Content-Disposition"
        response.headers["Content-Disposition"] = 'attachment; filename={}'.format(
            file_name.encode('utf-8').decode('ISO-8859-1'))
        return response

    def generate_excel(self, d, lang_dict):
        wb = Workbook()
        ws_seg_nor_f21 = wb.create_sheet(lang_dict['TOR_ORG'], 0)
        ws_seg_nor_f21.append([lang_dict['FILE_NAME'], lang_dict['TOR_GRADE'], lang_dict['PRED_PROB']])
        for each_r in d["seg_normal_f21"]:
            try:
                t = [each_r["name"], each_r["res"]["level"], each_r["res"]["probabilities"]]
            except:
                t = [each_r["name"], 'not found']
            ws_seg_nor_f21.append(t)

        ws_seg_enh_f21 = wb.create_sheet(lang_dict['TOR_EHD'], 1)
        ws_seg_enh_f21.append([lang_dict['FILE_NAME'], lang_dict['TOR_GRADE'], lang_dict['PRED_PROB']])
        for each_r in d["seg_enhance_f21"]:
            try:
                t = [each_r["name"], each_r["res"]["level"], each_r["res"]["probabilities"]]
            except:
                t = [each_r["name"], 'not found']
            ws_seg_enh_f21.append(t)

        ws_vas_nor_f2 = wb.create_sheet(lang_dict['HIST_ORG'], 2)
        ws_vas_nor_f2.append([lang_dict['FILE_NAME'], '0', '20', '40', '60', '80', '100', '120', '140', '160', '180'])
        for each_r in d["vascular_normal_f2"]:
            try:
                t = [each_r["name"]]
                t.extend(each_r["res"]["y"])
            except:
                t = [each_r["name"], 'not found']
            ws_vas_nor_f2.append(t)

        ws_vas_enh_f2 = wb.create_sheet(lang_dict['HIST_EHD'], 3)
        ws_vas_enh_f2.append([lang_dict['FILE_NAME'], '0', '20', '40', '60', '80', '100', '120', '140', '160', '180'])
        for each_r in d["vascular_enhance_f2"]:
            try:
                t = [each_r["name"]]
                t.extend(each_r["res"]["y"])
            except:
                t = [each_r["name"], 'not found']
            ws_vas_enh_f2.append(t)

        ws_vas_nor_f21 = wb.create_sheet(lang_dict['QUANT_ORG'], 4)
        ws_vas_nor_f21.append([lang_dict['FILE_NAME'], 'CNFL', 'CNFD', 'CTBD', 'CNBD'])
        for each_r in d["vascular_normal_f21"]:
            try:
                t = [each_r["name"], each_r["res"]["CNFL"], each_r["res"]["CNFD"], each_r["res"]["CTBD"], each_r["res"]["CNBD"]]
            except:
                t = [each_r["name"], 'not found']
            ws_vas_nor_f21.append(t)

        ws_vas_enh_f21 = wb.create_sheet(lang_dict['QUANT_EHD'], 5)
        ws_vas_enh_f21.append([lang_dict['FILE_NAME'], 'CNFL', 'CNFD', 'CTBD', 'CNBD'])
        for each_r in d["vascular_enhance_f21"]:
            try:
                t = [each_r["name"], each_r["res"]["CNFL"], each_r["res"]["CNFD"], each_r["res"]["CTBD"], each_r["res"]["CNBD"]]
            except:
                t = [each_r["name"], 'not found']
            ws_vas_enh_f21.append(t)

        ws_vas_nor_f5 = wb.create_sheet(lang_dict['NER_CHI_CO_ORG'], 6)
        ws_vas_nor_f5.append([lang_dict['FILE_NAME'], 'x', 'y'])
        for each_r in d['vascular_normal_f5']:
            try:
                name = each_r["name"]
                x_list = each_r['res']['x']
                y_list = each_r['res']['y']

                for e_x, e_y in zip(x_list, y_list):
                    e_t = [name, int(e_x), int(e_y)]
                    ws_vas_nor_f5.append(e_t)
            except:
                t = [each_r["name"], 'not found', 'not found']
                ws_vas_nor_f5.append(t)

        ws_vas_enh_f5 = wb.create_sheet(lang_dict['NER_CHI_CO_EHD'], 7)
        ws_vas_enh_f5.append([lang_dict['FILE_NAME'], 'x', 'y'])
        for each_r in d['vascular_enhance_f5']:
            try:
                name = each_r["name"]
                x_list = each_r['res']['x']
                y_list = each_r['res']['y']

                for e_x, e_y in zip(x_list, y_list):
                    e_t = [name, int(e_x), int(e_y)]
                    ws_vas_enh_f5.append(e_t)
            except:
                t = [each_r["name"], 'not found', 'not found']
                ws_vas_enh_f5.append(t)

        excel_name = tempfile.NamedTemporaryFile(suffix='.xlsx').name
        wb.save(excel_name)
        return excel_name

    def make_result_dict(self, seg_saver, vascular_saver, img_list):
        return {
            "seg_normal_f21": self.get_predict(img_list, seg_saver.NORMAL_2_1),
            "seg_enhance_f21": self.get_predict(img_list, seg_saver.ENHANCE_2_1),
            "vascular_normal_f2": self.get_predict(img_list, vascular_saver.NORMAL_2),
            "vascular_enhance_f2": self.get_predict(img_list, vascular_saver.ENHANCE_2),
            "vascular_normal_f21": self.get_predict(img_list, vascular_saver.NORMAL_3),
            "vascular_enhance_f21": self.get_predict(img_list, vascular_saver.ENHANCE_3),
            "vascular_normal_f5": self.get_predict(img_list, vascular_saver.NORMAL_TMP_5),
            "vascular_enhance_f5": self.get_predict(img_list, vascular_saver.ENHANCE_TMP_5)
        }

    def get_predict(self, img_list: list, search_path: str):
        # 根据图片名称进行扫盘
        result = []
        for each_img in img_list:
            file_name = os.path.join(search_path, each_img + ".txt")
            file_res = ParserTools.parser_from_file_to_str(file_name)
            if file_res == "":
                result.append({'name': each_img, 'res': ""})
            else:
                result.append({'name': each_img, 'res': json.loads(file_res)})
        return result

    def chang_suffix(self, img_list):
        # 服务器的图片统一按照PNG存储，所以需要改变后缀
        l = []
        for each_img in img_list:
            name = each_img.split(".")[0]
            l.append(name + ".png")
        return l

    def get_all_img(self, path: str):
        # 在all_img 为 true的时候进行扫盘
        img_list = []
        for each_file in os.listdir(path):
            img_list.append(each_file)
        return img_list
